import { message } from 'antd'
import axios from 'axios'
import { useEffect, useState } from 'react'

// 自定义hooks
function usePublish(type) {
  const [dataSource, setDataSource] = useState([])
  const { username } = JSON.parse(localStorage.getItem('token'))
  // 下线
  const downNews = (item) => {
    // console.log(item)
    setDataSource(dataSource.filter(i => i.id !== item.id))
    axios.patch(`/news/${item.id}`, {
      publishState: 3
    }).then(res => {
      message.success('下线成功')
    })
  }
  // 删除
  const deleteNews = (item) => {
    // console.log(item)
    setDataSource(dataSource.filter(i => i.id !== item.id))
    axios.delete(`/news/${item.id}`).then(res => {
      message.success('删除成功')
    })

  }
  // 发布
  const publishNews = (item) => {
    // console.log(item)
    setDataSource(dataSource.filter(i => i.id !== item.id))
    axios.patch(`/news/${item.id}`, {
      publishState: 2,
      publishTime: Date.now()
    }).then(res => {
      message.success('发布成功')
    })

  }

  useEffect(() => {
    axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(res => {
      console.log(res)
      setDataSource(res.data)
    })
  }, [username, type])

  return {
    dataSource,
    downNews,
    deleteNews,
    publishNews
  }
}

export default usePublish